<template>
  <div class="container" v-loading="loading">
    <!-- 工具栏 -->
    <div class="table-toolbar">
      <el-button link @click.stop="addNode" style="color: #1aa1fb">
        <el-icon style="margin-right: 3px"><Plus /></el-icon>
        新建节点
      </el-button>
      <!-- <el-button
        link
        @click="handleImport"
        style="--el-text-color-regular: #42464e"
      >
        <img
          style="display: inline-block; margin-right: 3px"
          src="@/assets/wbs/export.svg"
          alt=""
        />
        <span>检出</span>
      </el-button>
      <el-button
        link
        @click="handleAssociate"
        style="--el-text-color-regular: #42464e"
      >
        <img
          style="display: inline-block; margin-right: 3px"
          src="@/assets/wbs/file.svg"
          alt=""
        />
        <span>打开任务工作目录</span>
      </el-button> -->
    </div>

    <!-- 表格 -->
    <CLTable
      @show:records="handleShowRecords"
      :pageQuery="queryParams"
      :fields="referenceFields"
      :initial-data="tableData"
      line-height="low"
      :table-config="tableConfig"
      :more-actions="moreActions"
      @node-selected="handleNodeSelected"
      @on-more-action="handleMoreAction"
      @pagerChange="pagerChange"
      ref="cltableRef"
    >
      <template #bottomTool>
        <BottomTool
          :selectedFiles="selectedFiles"
          :tableData="tableData"
          @changeCheckbox="changeCheckbox"
          @batchExport="batchExport"
          @batchDelete="batchDelete"
        />
      </template>
    </CLTable>

    <!-- 导入 -->
    <FileUploaderDialog
      ref="fileUploadDialogRef"
      @UploadComplete="UploadComplete"
    />

    <!-- 编辑 -->
    <NameEditModal
      :activeNode="activeNode"
      ref="editNameRef"
      @handleCancel="handleCancel"
      @handleSure="handleSure"
    />

    <!-- 预览 -->
    <Preview ref="preViewRef" :src="preSrc" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { Plus } from "@element-plus/icons-vue";
  import CLTable from "@/components/CLTable/index.vue";
  import {
    deleteDataFlowItem,
    editDataFlow,
    deleteItem,
    editItem,
    uploadFile,
    createTaskData,
    getDataTree,
    bathDownLoadTaskFile,
    deleteDataFlowBatch,
  } from "./api.ts";
  import Preview from "./Preview.vue";
  import FileUploaderDialog from "./FileUploaderDialog.vue";
  import BottomTool from "./BottomTool.vue";
  import NameEditModal from "./NameEditModal.vue";
  import { download } from "@/utils/index";

  import DIR from "@/assets/wbs/dir.svg";

  const props = defineProps(["detail"]);
  const editNameRef = ref();
  const fileUploadDialogRef = ref();

  const activeNode = ref();
  const cltableRef = ref();
  const preSrc = ref(false);

  // 响应式数据
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const selectedFiles = ref<any[]>([]);
  const preViewRef = ref();
  // CLTable 字段配置
  const referenceFields = ref<any[]>([
    {
      id: 0,
      name: "",
      field: "index",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 1,
      name: "名称",
      field: "fileName",
      typex: "imagetext",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 2,
      name: "数据源",
      field: "source",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 3,
      name: "数据流",
      field: "remark",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
    {
      id: 4,
      name: "数据流状态",
      field: "remark",
      type: "text",
      invisible: true,
      checked: true,
      disable: false,
    },
  ]);

  // CLTable 配置
  const tableConfig = ref({
    tableH: "calc(100vh - 230px)",
    page: {
      showOperationsColumn: true,
      enable: true,
      pageSizes: [10, 20, 50, 100],
      size: "small",
      disabled: false,
      background: true,
      layout: "total, sizes, prev, pager, next, jumper",
    },
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 200, //自定义操作列宽度
    borderMode: "none", // 表格边框模式，none为无边框
    rightFrozenColCount: 1, // 冻结后面列数
    tree: {
      enabled: true,
      column: 1,
    },
  });

  // 更多操作配置
  const moreActions = ref([
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
    { key: "import", label: "导入", invisible: ["showImport"] },
    { key: "export", label: "导出" },
    { key: "preview", label: "预览", invisible: ["showPreview"] },
    // { key: "delete", label: "关联" },
    // { key: "delete", label: "检出" },
  ]);

  const handleMoreAction = (actionKey: string, node: any) => {
    const KEYMAP: any = {
      edit: handleEdit,
      preview: handlePreview,
      delete: handleDelete,
      export: handleExport,
      import: handleImport,
    };
    KEYMAP[actionKey]?.(node);
  };

  /**
   * @description 处理选中与否
   */
  const changeCheckbox = async (val: boolean) => {
    const tableInstalce = await cltableRef.value?.getTableInstance();
    tableInstalce.setCellCheckboxState(0, 0, val);
    if (val) {
      selectedFiles.value = tableData.value;
    } else {
      selectedFiles.value = [];
    }
  };
  /**
   * @description 文件上传成功
   */
  const UploadComplete = async (data: any) => {
    loading.value = true;
    try {
      const { successFiles, description } = data ?? {};
      const params = successFiles.map((ele: any) => ({
        fileId: ele?.docId ?? "",
        fileName: ele?.name ?? "",
        filePath: ele?.raw?.webkitRelativePath ?? "",
        projectId: props?.detail?.projectId,
        taskId: props?.detail?.id,
        remark: description ?? "",
        source: "UPLOAD",
        type: "INPUT_DATA",
        dataflowId: activeNode.value.id ?? "",
      }));
      await uploadFile(params);
      loadData(1, 20);
    } catch (error) {}
  };

  /**
   * @description 处理选中值
   */
  const handleShowRecords = (records: any[]) => {
    selectedFiles.value = records;
  };

  /**
   * 批量导出
   */
  const batchExport = async () => {
    loading.value = true;
    try {
      const params = selectedFiles.value.map((ele) => ({
        fileId: ele.fileId ?? ele.id,
        fileName: ele?.fileName ?? ele?.name?.["zh_CN"],
        dataflowId: ele?.id ?? "",
      }));
      const res = await bathDownLoadTaskFile(params);
      download(res, "application/zip;charset=UTF-8", `压缩包_${Date.now()}`);
      ElMessage.success("批量导出成功");
    } catch (error) {
      ElMessage.error("批量导出失败");
    } finally {
      loading.value = false;
    }
  };

  /**
   * 批量删除
   */
  const batchDelete = async () => {
    loading.value = true;
    try {
      await ElMessageBox.confirm(`确定要批量删除这些文件吗？`, "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      const nodeIds = selectedFiles.value.map((e) => e.id);
      await deleteDataFlowBatch(nodeIds.toString());
      ElMessage.success("删除成功");
      loadData(1, 20);
    } catch (error) {
      ElMessage.error("删除失败");
    }
  };

  /**
   * @description 新建节点
   */
  const addNode = async () => {
    loading.value = true;
    try {
      const params = {
        name: {
          zh_CN: `文件夹_${tableData?.value?.length}`,
        },
        projectId: props?.detail?.projectId,
        taskId: props?.detail?.id,
        source: "UPLOAD",
        type: "INPUT_DATA",
      };
      await createTaskData(params);
      loadData(1, 20);
    } catch (error) {}
  };

  /**
   * @description 监听分页变化
   */
  const pagerChange = (args: any) => {
    loadData(args.currentPage, args.pageSize);
  };

  /**
   * @description 处理取消
   */
  const handleCancel = () => {
    editNameRef.value.visible = false;
    activeNode.value = null;
  };

  /**
   * @description 处理确定
   */
  const handleSure = async (fileName: string) => {
    loading.value = true;
    try {
      const params = {
        ...(activeNode?.value ?? {}),
        fileName,
        name: {
          zh_CN: fileName,
        },
      };
      const children = activeNode.value.children;
      if (!children) {
        await editItem(params);
        loadData(1, 20);
        editNameRef.value.visible = false;
        return false;
      }
      await editDataFlow(params);
      loadData(1, 20);
      editNameRef.value.visible = false;
    } catch (error) {}
  };

  // 计算属性
  const queryParams = ref({
    pageNo: 1,
    pageSize: 20,
    total: 0,
  });

  // 方法
  const loadData = async (numberPage: number, sizePage: number) => {
    loading.value = true;
    try {
      const params = {
        fileSearchRequest: {
          conditions: [
            {
              field: "type",
              operator: "=",
              value: "INPUT_DATA",
            },
            {
              field: "projectId",
              operator: "=",
              value: props?.detail?.projectId,
            },
            {
              field: "taskId",
              operator: "=",
              value: props?.detail?.id,
            },
          ],
          pageNo: numberPage ?? 1,
          pageSize: sizePage ?? 10,
        },
        folderSearchRequest: {
          conditions: [
            {
              field: "type",
              operator: "=",
              value: "INPUT_DATA",
            },
            {
              field: "projectId",
              operator: "=",
              value: props?.detail?.projectId,
            },
            {
              field: "taskId",
              operator: "=",
              value: props?.detail?.id,
            },
          ],
          pageNo: numberPage ?? 1,
          pageSize: sizePage ?? 10,
        },
      };

      // 如果需要调用真实 API，取消下面的注释
      const { result, pageNo, pageSize, total } = await getDataTree(params);
      queryParams.value = {
        pageNo,
        pageSize,
        total,
      };

      tableData.value =
        (result as any[])?.map((ele) => ({
          ...ele,
          fileName: ele?.name?.["zh_CN"],
          children: (ele.dataflowFileList as any[]).map((e) => ({
            ...e,
            showPreview: true,
            showImport: false,
          })),
          showPreview: false,
          showImport: true,
          imageUrl: DIR,
        })) ?? [];
      selectedFiles.value = [];
    } catch (error) {
      ElMessage.error("加载数据失败");
    } finally {
      loading.value = false;
    }
  };

  const handleNodeSelected = (nodes: any[]) => {
    selectedFiles.value = nodes;
  };

  /**
   * @description 处理单行导出
   */

  const handleExport = async (node: any) => {
    loading.value = true;
    try {
      const children = node.children;
      if (children) {
        const params = [
          {
            dataflowId: node?.id ?? "",
            fileId: node.id,
            fileName: node.name["zh_CN"],
          },
        ];
        const arr = node.fileName.split(".");
        const res = await bathDownLoadTaskFile(params);
        download(res, "application/zip;charset=UTF-8", arr[0]);
        ElMessage.success("导出成功");
        return false;
      }
      const params = [
        {
          fileId: node.fileId,
          fileName: node.fileName,
        },
      ];
      const arr = node.fileName.split(".");
      const res = await bathDownLoadTaskFile(params);
      download(res, `image/${arr[arr.length - 1]};charset=UTF-8`, arr[0]);
      ElMessage.success("导出成功");
    } catch (error) {
      ElMessage.error("导出失败");
    } finally {
      loading.value = true;
    }
  };

  /**
   * @description 处理单行导入
   */
  const handleImport = (node: any) => {
    activeNode.value = node;
    if (fileUploadDialogRef.value) {
      fileUploadDialogRef.value.visible = true;
    }
  };

  const handleEdit = (node: any) => {
    activeNode.value = node;
    editNameRef.value.visible = true;
  };

  /**
   * @description 处理预览
   */

  const handlePreview = (node: any) => {
    preSrc.value = node;
    preViewRef.value.visible = true;
  };

  const handleDelete = async (node: any) => {
    try {
      const children = node.children;
      await ElMessageBox.confirm(
        `确定要删除${children ? "文件" : "文件夹"} "${node.fileName}" 吗？`,
        "确认删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        },
      );
      loading.value = true;
      if (!children) {
        await deleteItem(node.id);
        ElMessage.success("删除成功");
        loadData(1, 20);
        return false;
      }
      // TODO: 调用删除 API
      await deleteDataFlowItem(node.id);
      ElMessage.success("删除成功");
      loadData(1, 20);
    } catch (error) {
      ElMessage.error("删除失败");
    }
  };

  // 生命周期
  onMounted(async () => {
    loadData(1, 20);
  });

  // 暴露方法给父组件
  defineExpose({
    loadData,
    refresh: loadData,
  });
</script>

<style scoped lang="scss">
  .container {
    box-sizing: border-box;
    padding-right: 10px;
    margin-top: 2px;
    .table-toolbar {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px 0px;
      color: #5e5e5e;
      font-size: 14px;

      :deep(.el-button.is-link) {
        font-weight: 400;
      }
    }
  }

  .relation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
</style>
